package com.chrelyonly.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Console;
import com.chrelyonly.controllerstatic.WxSeptConStatic;
import com.chrelyonly.util.myRes.AjaxJson;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author chrelyonly
 */
@RestController
@CrossOrigin
@AllArgsConstructor
public class SeptCon {
    /**
     * 限制提交次数
     */
    private static final Map<String, Integer> REDIS = new LinkedHashMap<>();


    /**
     * 早上
     */
    private final static String AM = "08:30:00";
    /**
     * 晚上
     */
    private final static String PM = "21:30:00";
    private final WxSeptConStatic wxSeptConStatic;

    /**
     * 方法描述 小米接口
     * 用于微信 支付宝步数
     *
     * @param name pwd sept email
     * @return AjaxJson
     * @author chrelyonly
     * @date 2021/12/26 12:14
     * @since 1.0
     */
    @RequestMapping("/wxSept")
    public AjaxJson wxSept(String name, String pwd, String sept, String email, HttpServletRequest httpServletRequest) throws ParseException {


        //        判断时间是否在时间断内
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//      早上
        Date am = sdf.parse(AM);
//        晚上
        Date pm = sdf.parse(PM);
        final String format = sdf.format(sdf2.parse(DateUtil.now()));
//        现在
        Date toTime = sdf.parse(format);
//        当前要大于 开始时间
        int i = toTime.compareTo(am);
//        如果不大于
        if (i < 0) {
            return AjaxJson.error("还未到提交时间");
        }
//        如果超过时间
        int j = toTime.compareTo(pm);
        if (j > 0) {
            return AjaxJson.error("已超过提交时间");
        }
//        判断是否提交过
        Integer integer = REDIS.get(name);
        if (integer == null) {
            integer = 1;
        }
        Console.log("该用户" + DateUtil.today() + "第" + integer + "次提交");
        if (integer > 3) {
            return AjaxJson.error("多次提交");
        } else {

            REDIS.put(name, ++integer);
        }
        if (email == null || "".equals(email)) {
            email = "1172576293@qq.com";
        }
        return wxSeptConStatic.wxSept(name, pwd, sept, email);
    }

    /**
     * 清理限制的提交次数
     *
     * @return
     */
    @RequestMapping("/cleanRedis")
    public String cleanRedis() {
        Console.log("当前redis" + REDIS);
        REDIS.clear();
        Console.log("清理后redis" + REDIS);
        return "ok";
    }
}
